package 队列;

/**
 * @author: 大怪
 * @email: 962527441@qq.com
 */

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 题目：
 * 给定一棵二叉树的根节点 root ，请找出该二叉树中每一层的最大值
 *
 * 示例1：
 *
 * 输入: root = [1,3,2,5,3,null,9]
 * 输出: [1,3,9]
 */
public class 二叉树每层的最大值 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    class Solution {
        public List<Integer> largestValues(TreeNode root) {
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            List<Integer> list = new ArrayList<Integer>();
            if (root == null) {
                return list;
            }
            queue.add(root);
            while(!queue.isEmpty()) {
                int max = Integer.MIN_VALUE;
                int n = queue.size();
                for (int i = 0; i < n; i++) {
                    TreeNode node = queue.poll();
                    max = Math.max(max, node.val);

                    if (node.left!=null) {
                        queue.add(node.left);
                    }

                    if (node.right!=null) {
                        queue.add(node.right);
                    }
                }
                list.add(max);
            }
            return list;
        }
    }

}
